import os
import time
import logging
from PyQt5.QtWidgets import QMainWindow, \
                            QFileDialog, \
                            QMessageBox
from RcLogAnalyzer.gui.main_window_ui import Ui_MainWindow
from RcLogAnalyzer.scripts.setting import global_setting
from RcLogAnalyzer.pyqt5.thread_log_analyze import ThreadLogAnalyze
from RcLogAnalyzer.pyqt5.thread_rcg_output import ThreadRcgOutput


class MainWindow(QMainWindow, Ui_MainWindow):
    total_task_num = 0
    current_task_num = 0
    analyze_result = {'lname': '', 'rname': '',
                      'lscore': 0, 'rscore': 0,
                      'l_pass_num': 0, 'r_pass_num': 0,
                      'l_intercept_num': 0, 'r_intercept_num': 0,
                      'l_dribble_num': 0, 'r_dribble_num': 0,
                      'l_long_pass': 0, 'r_long_pass': 0,
                      'l_normal_pass': 0, 'r_normal_pass': 0,
                      'l_short_pass': 0, 'r_short_pass': 0,
                      'l_through_pass': 0, 'r_through_pass': 0}

    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)

        # 初始化logger
        self.logger = logging.getLogger('main_window')
        self.logger.setLevel(logging.INFO)

        stream_handler = logging.StreamHandler()
        stream_handler.setLevel(logging.INFO)
        stream_handler.setFormatter(logging.Formatter('%(name)s - %(levelname)s - %(message)s'))

        self.logger.addHandler(stream_handler)
        self.logger.info('Logger init finish.')

        # 读取设置
        global_setting.read_file()
        self.logger.info('read setting finish.')

        # 信号与槽连接
        self.connect_all()
        self.logger.info('Signal and slot connect finish.')

        # 界面配置
        self.tab_widget_main.setCurrentIndex(0)     # 初始界面为log

        # log
        self.push_button_log_start.setEnabled(False)
        self.progress_bar_log.setValue(0)
        self.stacked_widget_log.setCurrentIndex(0)
        if global_setting.log_output_dataset == 1:
            self.check_box_through_pass_dataset.setChecked(True)
        else:
            self.check_box_through_pass_dataset.setChecked(False)
        if global_setting.log_output_result == 1:
            self.check_box_output_result.setChecked(True)
        else:
            self.check_box_output_result.setChecked(False)
        # rcg
        self.line_edit_rcg_save_folder.setText(global_setting.rcg_save_folder)
        self.push_button_rcg_start.setEnabled(False)
        self.progress_bar_rcg.setValue(0)

        self.logger.info('Init ui finish.')

    def closeEvent(self, event):
        self.logger.info('Func: closeEvent')
        # 保存设置
        global_setting.save_file()
        self.logger.info('Save setting file finish.')

        event.accept()

    def connect_all(self):
        self.logger.info('Func: connect_all')
        # log
        self.push_button_log_setting.clicked.connect(self.push_button_log_setting_clicked)
        self.push_button_log_select.clicked.connect(self.push_button_log_select_clicked)
        self.push_button_log_start.clicked.connect(self.push_button_log_start_clicked)
        self.check_box_through_pass_dataset.clicked.connect(self.check_box_through_pass_dataset_clicked)
        self.check_box_output_result.clicked.connect(self.check_box_output_result_clicked)

        # rcg
        self.push_button_rcg_select.clicked.connect(self.push_button_rcg_select_clicked)
        self.push_button_rcg_select_folder.clicked.connect(self.push_button_rcg_select_folder_clicked)
        self.push_button_rcg_start.clicked.connect(self.push_button_rcg_start_clicked)

    # ============================== log ==============================
    def check_box_through_pass_dataset_clicked(self, is_checked):
        self.logger.info('Func: check_box_through_pass_dataset_clicked')
        if is_checked:
            global_setting.log_output_dataset = 1
        else:
            global_setting.log_output_dataset = 0

    def check_box_output_result_clicked(self, is_checked):
        self.logger.info('Func: check_box_output_result_clicked')
        if is_checked:
            global_setting.log_output_result = 1
        else:
            global_setting.log_output_result = 0

    def push_button_log_setting_clicked(self):
        self.logger.info('Func: push_button_log_setting_clicked')
        if self.stacked_widget_log.currentIndex() == 0:
            self.stacked_widget_log.setCurrentIndex(1)
            self.push_button_log_setting.setText('return')
        else:
            self.stacked_widget_log.setCurrentIndex(0)
            self.push_button_log_setting.setText('analyze setting')

        return

    def push_button_log_select_clicked(self):
        self.logger.info('Func: push_button_log_select_clicked')
        files, _ = QFileDialog.getOpenFileNames(self,
                                                '选择rcl文件',
                                                global_setting.log_dir,
                                                'rcl日志文件(*.rcl)')
        if len(files) == 0:
            self.logger.info('没有选择rcl文件')
            return

        # 清空列表框
        while self.list_widget_log.count() != 0:
            self.list_widget_log.takeItem(0)

        # 获取rcl文件路径并保存到全局设置
        global_setting.log_dir = os.path.split(files[0][:-1])[0]

        # 添加到列表
        for file in files:
            self.list_widget_log.addItem(file)

        self.push_button_log_start.setEnabled(True)

        self.statusbar.showMessage('添加' + str(len(files)) + '个文件')

        self.logger.info('push button log select clicked')
        return

    def push_button_log_start_clicked(self):
        self.logger.info('Func: push_button_log_start_clicked')
        item_count = self.list_widget_log.count()
        if item_count == 0:
            self.logger.warning('no item in list')
            return

        self.progress_bar_log.setValue(0)
        self.progress_bar_log.setMaximum(item_count)
        self.list_widget_log.setCurrentRow(0)
        self.statusbar.showMessage('正在处理（1/' + str(item_count) + '）')

        # 启动线程
        # if global_setting.log_output_dataset == 1:
        if os.path.exists(os.path.join(os.getcwd(), 'output')) == False:
            os.mkdir(os.path.join(os.getcwd(), 'output'))
        if os.path.exists(os.path.join(os.getcwd(), 'output/dataset')) == False:
            os.mkdir(os.path.join(os.getcwd(), 'output/dataset'))
        self.total_task_num = self.list_widget_log.count()
        self.current_task_num = 0
        self.thread_log_analyze = ThreadLogAnalyze()
        self.thread_log_analyze.trigger.connect(self.log_analyze_slot)
        self.thread_log_analyze.processing_file_name = self.list_widget_log.item(self.current_task_num).text()
        self.thread_log_analyze.data_save_path = os.path.join(os.getcwd(), 'output/dataset')
        self.push_button_log_select.setEnabled(False)
        self.thread_log_analyze.start()

        self.logger.info('push button log start clicked')
        return

    def log_analyze_slot(self):
        self.logger.info('Func: log_analyze_slot')
        self.current_task_num += 1  # 当前任务+1
        self.progress_bar_log.setValue(self.current_task_num) # 进度条+1

        self.analyze_result['l_through_pass'] += self.thread_log_analyze.analyze_result['l_through_pass']

        self.logger.debug(str(self.current_task_num))
        # 处理完成
        if self.current_task_num == self.total_task_num:
            if global_setting.log_output_result == 1:   # 是否输出结果
                self.output_result()     # 输出结果文件

            self.statusbar.showMessage('全部完成！')
            self.push_button_log_select.setEnabled(True)
            data_name = os.path.split(self.list_widget_log.item(self.current_task_num-1).text())[1]
            data_name = os.path.join(os.path.join(os.getcwd(), 'output/dataset'), data_name[:-3]+'db')
            os.remove(data_name)
            QMessageBox.information(self, '完成', '全部分析完成！')
        # 处理进行中
        else:
            self.list_widget_log.setCurrentRow(self.current_task_num)
            self.statusbar.showMessage('正在处理（' + str(self.current_task_num+1) + '/' +
                                       str(self.total_task_num) + '）')
            if self.thread_log_analyze.isRunning():
                self.thread_log_analyze.wait()
            data_name = os.path.split(self.list_widget_log.item(self.current_task_num-1).text())[1]
            data_name = os.path.join(os.path.join(os.getcwd(), 'output/dataset'), data_name[:-3]+'db')
            os.remove(data_name)
            self.thread_log_analyze.processing_file_name = self.list_widget_log.item(self.current_task_num).text()
            self.thread_log_analyze.data_save_path = os.path.join(os.getcwd(), 'output/dataset')
            self.thread_log_analyze.start()

    def output_result(self):
        self.logger.info('Func: output_result')
        if os.path.exists(os.path.join(os.getcwd(), 'output')) == False:
            os.mkdir(os.path.join(os.getcwd(), 'output'))
        if os.path.exists(os.path.join(os.getcwd(), 'output/result')) == False:    # 如果当前目录下result文件夹不存在
            os.mkdir(os.path.join(os.getcwd(), 'output/result'))   # 创建result文件夹
        self.logger.debug('输出结果文件： '
                          + time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()-2592000))
                          + '.txt')
        result_write = open('./output/result/result_' +
                            time.strftime('%Y%m%d%H%M',
                                          time.localtime(time.time()-2592000)) + '.txt', 'a')

        result_write.write('Total left teeam through pass num : ')
        result_write.write(str(self.analyze_result['l_through_pass']) + '\n')
        result_write.write('Game number : ')
        result_write.write(str(self.total_task_num) + '\n')
        result_write.write('Averaging number per game : ')
        result_write.write(str(round(self.analyze_result['l_through_pass'] / self.total_task_num, 4)))
        result_write.close()

    # ============================== rcg ==============================
    def push_button_rcg_select_folder_clicked(self):
        self.logger.info('Func: push_button_rcg_select_folder_clicked')
        save_folder = QFileDialog.getExistingDirectory(self, '选择数据目录', global_setting.rcg_save_folder)
        if dir == '':
            self.logger.info('没有选择文件夹')
            return

        self.line_edit_rcg_save_folder.setText(dir)

    def push_button_rcg_select_clicked(self):
        self.logger.info('Func: push_button_rcg_select_clicked')
        files, _ = QFileDialog.getOpenFileNames(self,
                                                '选择rcg文件',
                                                global_setting.rcg_dir,
                                                'rcg日志文件(*.rcg)')
        if len(files) == 0:
            self.logger.info('没有选择rcg文件')
            return

        # 清空列表框
        while self.list_widget_rcg.count() != 0:
            self.list_widget_rcg.takeItem(0)

        # 获取rcl文件路径并保存到全局设置
        global_setting.rcg_dir = os.path.split(files[0][:-1])[0]

        # 添加到列表
        for file in files:
            self.list_widget_rcg.addItem(file)

        self.push_button_rcg_start.setEnabled(True)

        self.statusbar.showMessage('添加' + str(len(files)) + '个rcg文件')

        self.logger.info('push button rcg select clicked')
        return

    def push_button_rcg_start_clicked(self):
        self.logger.info('Func: push_button_rcg_start_clicked')
        item_count = self.list_widget_rcg.count()
        if item_count == 0:
            self.logger.warning('no item in list')
            return

        self.progress_bar_rcg.setValue(0)
        self.progress_bar_rcg.setMaximum(item_count)
        self.list_widget_rcg.setCurrentRow(0)
        self.statusbar.showMessage('正在处理（1/' + str(item_count) + '）')

        # 启动线程
        self.total_task_num = self.list_widget_rcg.count()
        self.current_task_num = 0
        self.thread_rcg_output = ThreadRcgOutput()
        self.thread_rcg_output.trigger.connect(self.rcg_output_slot)
        self.thread_rcg_output.processing_file_name = self.list_widget_rcg.item(self.current_task_num).text()[:-1]+'g'
        self.thread_rcg_output.data_save_path = global_setting.rcg_save_folder
        if self.radio_button_save_as_db.isChecked():
            self.thread_rcg_output.save_format = 0
        else:
            self.thread_rcg_output.save_format = 1
        self.push_button_rcg_select_folder.setEnabled(False)
        self.push_button_rcg_select.setEnabled(False)
        self.thread_rcg_output.start()

    def rcg_output_slot(self):
        self.logger.info(rcg_output_slot)
        self.current_task_num += 1
        self.progress_bar_rcg.setValue(self.current_task_num)
        # 处理完成
        if self.current_task_num == self.total_task_num:
            self.statusbar.showMessage('全部完成！')
            self.push_button_rcg_select_folder.setEnabled(True)
            self.push_button_rcg_select.setEnabled(True)
            QMessageBox.information(self, '完成', '全部输出完成！')
        # 处理进行中
        else:
            self.list_widget_rcg.setCurrentRow(self.current_task_num)
            self.statusbar.showMessage('正在处理（' + str(self.current_task_num+1) + '/' +
                                       str(self.total_task_num) + '）')
            if self.thread_rcg_output.isRunning():
                self.thread_rcg_output.wait()
            self.thread_rcg_output.processing_file_name = self.list_widget_rcg.item(self.current_task_num).text()[:-1]+'g'
            self.thread_rcg_output.data_save_path = global_setting.rcg_save_folder
            if self.radio_button_save_as_db.isChecked():
                self.thread_rcg_output.save_format = 0
            else:
                self.thread_rcg_output.save_format = 1
            self.thread_rcg_output.start()

